#include <stdio.h>
#include <stdlib.h>
#include "start.h"
#include "mySocket.h"
#include "proto.h"

void sig_alrm(int signo)
{
	msgh.cmd = HEART_BEAT;
	sprintf(buf, "%s", myUID);
	msgh.length = strlen(buf) + 1;
	writeMsg(sockfd, &msgh, buf);
	alarm(10);
}

char **nicknameList;
char **uIDList;
int n;

void getUID()
{
	char *res = NULL;
	
	nicknameList = (char **)malloc(sizeof(char *) * 100);
	uIDList = (char **)malloc(sizeof(char *) * 100);
	
	res = strtok(buf, "\n");
	while (res != NULL)
	{
		nicknameList[n] = (char *)malloc(LEN);
		uIDList[n] = (char *)malloc(LEN);
		sscanf(res, "%s%s", uIDList[n], nicknameList[n]);
		n++;
		res = strtok(NULL, "\n");
	}
	nicknameList[n] = (char *)malloc(LEN);
	uIDList[n] = (char *)malloc(LEN);
	strcpy(nicknameList[n], "Exit");
	strcpy(uIDList[n], "exit");
	n++;
	nicknameList[n] = (char *)NULL;
	uIDList[n] = (char *)NULL;
	n++;
	printf("%d\n", n);
}

int main(int argc, char *argv[])
{
	char uID[LEN + 1] = {0}, pwd[LEN + 1] = {0};
	int rc;
	char *IP;
	int port;
	pthread_t ltid, ptid;
	SAI addr;
	socklen_t len;
	char *uIP;
	
	if (argc != 3)
	{
		printf("Usage : %s IP port\n", argv[0]);
		return 1;
	}
	IP = argv[1];
	port = atoi(argv[2]);
	
	rc = start(uID, pwd);
	sockfd = init(port, IP, &sockAddr);
	
	signal(SIGALRM, sig_alrm);
	
	if (rc == 0)
	{
		msgh.cmd = REGISTER;
		sprintf(buf, "%s %s", uID, pwd);
		msgh.length = strlen(buf) + 1;
		writeMsg(sockfd, &msgh, buf);
		
		readMsg(sockfd, &msgh, buf);
		printf("Your uID is %s\n", buf);
	}
	else
	{
		msgh.cmd = LOGIN;
		len = sizeof(addr);
		getsockname(sockfd, (SA *) &addr, &len);
		uIP = inet_ntoa(addr.sin_addr);
		sprintf(buf, "%s %s %s", uID, pwd, uIP);
		msgh.length = strlen(buf) + 1;
		writeMsg(sockfd, &msgh, buf);
		
		readMsg(sockfd, &msgh, buf);
		if (msgh.error)
			printf("Login error\n");
		else
		{
			strcpy(myUID, uID);
			msgh.cmd = FRIEND_LIST;
			sprintf(buf, "%s", myUID);
			msgh.length = strlen(buf) + 1;
			writeMsg(sockfd, &msgh, buf);
			
			readMsg(sockfd, &msgh, buf);
			printf("%s\n", buf);
			pthread_create(&ltid, 0, Listen, 0);
			pthread_create(&ptid, 0, p2pFunc, &sockfd);
			userList.clear();
			alarm(30);
			
			getUID();
			mainGUI(nicknameList, uIDList, n);
		}
	}
	
	return 0;
}
